using System;
using System.Drawing;
using System.Collections;
using System.ComponentModel;
using System.Windows.Forms;
using System.Data;

using SftTreeLib70;
using AxSftTreeLib70;
using Softelvdm.OLEConvert;

namespace Email
{
    /// <summary>
    /// Summary description for Form1.
    /// </summary>
    public class Form1 : System.Windows.Forms.Form
    {
        private AxSftTreeLib70.AxSftTree axSftTree1;
        public System.Windows.Forms.TextBox EditControl;
        public System.Windows.Forms.Button Command1;
        public System.Windows.Forms.ToolTip ToolTip1;
        public System.Windows.Forms.PictureBox Attach;
        private Softelvdm.OCXHelper.SftHelperComponent sftHelperComponent1;
        private System.ComponentModel.IContainer components;

        public Form1()
        {
            //
            // Required for Windows Form Designer support
            //
            InitializeComponent();

            //
            // TODO: Add any constructor code after InitializeComponent call
            //
        }

        /// <summary>
        /// Clean up any resources being used.
        /// </summary>
        protected override void Dispose( bool disposing )
        {
            if( disposing )
            {
                if (components != null) 
                {
                    components.Dispose();
                }
            }
            base.Dispose( disposing );
        }

        #region Windows Form Designer generated code
		/// <summary>
		/// Required method for Designer support - do not modify
		/// the contents of this method with the code editor.
		/// </summary>
		private void InitializeComponent()
		{
            this.components = new System.ComponentModel.Container();
            System.Resources.ResourceManager resources = new System.Resources.ResourceManager(typeof(Form1));
            this.axSftTree1 = new AxSftTreeLib70.AxSftTree();
            this.EditControl = new System.Windows.Forms.TextBox();
            this.Command1 = new System.Windows.Forms.Button();
            this.ToolTip1 = new System.Windows.Forms.ToolTip(this.components);
            this.Attach = new System.Windows.Forms.PictureBox();
            this.sftHelperComponent1 = new Softelvdm.OCXHelper.SftHelperComponent(this.components);
            ((System.ComponentModel.ISupportInitialize)(this.axSftTree1)).BeginInit();
            this.SuspendLayout();
            // 
            // axSftTree1
            // 
            this.axSftTree1.Anchor = (((System.Windows.Forms.AnchorStyles.Top | System.Windows.Forms.AnchorStyles.Bottom) 
                | System.Windows.Forms.AnchorStyles.Left) 
                | System.Windows.Forms.AnchorStyles.Right);
            this.axSftTree1.Location = new System.Drawing.Point(8, 8);
            this.axSftTree1.Name = "axSftTree1";
            this.axSftTree1.OcxState = ((System.Windows.Forms.AxHost.State)(resources.GetObject("axSftTree1.OcxState")));
            this.axSftTree1.Size = new System.Drawing.Size(472, 360);
            this.axSftTree1.TabIndex = 0;
            this.axSftTree1.ItemDblClick += new AxSftTreeLib70._DSftTreeEvents_ItemDblClickEventHandler(this.axSftTree1_ItemDblClick);
            this.axSftTree1.EditAllowed += new AxSftTreeLib70._DSftTreeEvents_EditAllowedEventHandler(this.axSftTree1_EditAllowed);
            this.axSftTree1.EditEnding += new AxSftTreeLib70._DSftTreeEvents_EditEndingEventHandler(this.axSftTree1_EditEnding);
            this.axSftTree1.ItemClick += new AxSftTreeLib70._DSftTreeEvents_ItemClickEventHandler(this.axSftTree1_ItemClick);
            this.axSftTree1.EditInitializing += new AxSftTreeLib70._DSftTreeEvents_EditInitializingEventHandler(this.axSftTree1_EditInitializing);
            this.axSftTree1.CaretChange += new AxSftTreeLib70._DSftTreeEvents_CaretChangeEventHandler(this.axSftTree1_CaretChange);
            this.axSftTree1.EditValidate += new AxSftTreeLib70._DSftTreeEvents_EditValidateEventHandler(this.axSftTree1_EditValidate);
            this.axSftTree1.EditNavigating += new AxSftTreeLib70._DSftTreeEvents_EditNavigatingEventHandler(this.axSftTree1_EditNavigating);
            // 
            // EditControl
            // 
            this.EditControl.AcceptsReturn = true;
            this.EditControl.AutoSize = false;
            this.EditControl.BackColor = System.Drawing.SystemColors.Window;
            this.EditControl.BorderStyle = System.Windows.Forms.BorderStyle.FixedSingle;
            this.EditControl.Cursor = System.Windows.Forms.Cursors.IBeam;
            this.EditControl.Font = new System.Drawing.Font("Microsoft Sans Serif", 8.25F, System.Drawing.FontStyle.Regular, System.Drawing.GraphicsUnit.Point, ((System.Byte)(0)));
            this.EditControl.ForeColor = System.Drawing.SystemColors.WindowText;
            this.EditControl.Location = new System.Drawing.Point(488, 80);
            this.EditControl.MaxLength = 0;
            this.EditControl.Name = "EditControl";
            this.EditControl.RightToLeft = System.Windows.Forms.RightToLeft.No;
            this.EditControl.Size = new System.Drawing.Size(73, 19);
            this.EditControl.TabIndex = 4;
            this.EditControl.Text = "EditControl";
            this.EditControl.Visible = false;
            // 
            // Command1
            // 
            this.Command1.Anchor = (System.Windows.Forms.AnchorStyles.Top | System.Windows.Forms.AnchorStyles.Right);
            this.Command1.BackColor = System.Drawing.SystemColors.Control;
            this.Command1.Cursor = System.Windows.Forms.Cursors.Default;
            this.Command1.DialogResult = System.Windows.Forms.DialogResult.Cancel;
            this.Command1.Font = new System.Drawing.Font("Microsoft Sans Serif", 8.25F, System.Drawing.FontStyle.Regular, System.Drawing.GraphicsUnit.Point, ((System.Byte)(0)));
            this.Command1.ForeColor = System.Drawing.SystemColors.ControlText;
            this.Command1.Location = new System.Drawing.Point(488, 8);
            this.Command1.Name = "Command1";
            this.Command1.RightToLeft = System.Windows.Forms.RightToLeft.No;
            this.Command1.Size = new System.Drawing.Size(73, 24);
            this.Command1.TabIndex = 3;
            this.Command1.Text = "&Close";
            this.Command1.Click += new System.EventHandler(this.Command1_Click);
            // 
            // Attach
            // 
            this.Attach.Cursor = System.Windows.Forms.Cursors.Default;
            this.Attach.Image = ((System.Drawing.Bitmap)(resources.GetObject("Attach.Image")));
            this.Attach.Location = new System.Drawing.Point(488, 56);
            this.Attach.Name = "Attach";
            this.Attach.Size = new System.Drawing.Size(10, 16);
            this.Attach.TabIndex = 5;
            this.Attach.TabStop = false;
            this.Attach.Visible = false;
            // 
            // Form1
            // 
            this.AutoScaleBaseSize = new System.Drawing.Size(5, 13);
            this.CancelButton = this.Command1;
            this.ClientSize = new System.Drawing.Size(568, 375);
            this.Controls.AddRange(new System.Windows.Forms.Control[] {
                                                                          this.Command1,
                                                                          this.Attach,
                                                                          this.axSftTree1,
                                                                          this.EditControl});
            this.Name = "Form1";
            this.Text = "Softel vdm, Inc. - Email Sample";
            this.Load += new System.EventHandler(this.Form1_Load);
            ((System.ComponentModel.ISupportInitialize)(this.axSftTree1)).EndInit();
            this.ResumeLayout(false);

        }
		#endregion

        private int m_InboxFolder = 0;      // IDs for various top-level folders
        private int m_OutboxFolder = 0;
        private int m_SavedFolder = 0;
        private int m_DeletedFolder = 0;
        private stdole.IFontDisp m_BoldFont = null; // saved bold font
        // in case many cells use the same font, it preserves resources to 
        // save one instance of an OLE font object

        /// <summary>
        /// The main entry point for the application.
        /// </summary>
        [STAThread]
        static void Main() 
        {
            Application.Run(new Form1());
        }
        //--locate-marker--

        private void Command1_Click(object sender, System.EventArgs e) {
            Application.Exit();
        }

        private void Form1_Load(object sender, System.EventArgs e) {
            int ItemIndex;
            m_InboxFolder = AddFolder("Inbox", "Viewed and unviewed mail", 10);
                AddMessage(1, "support@softelvdm.com", "Re: A support question", "10/09/05", 88, true);
                AddMessage(1, "anyone@acompany.com", "Re: Why did you say that", "10/10/05", 5, false);
                AddMessage(1, "anyone@acompany.com", "Re: You're fired", "10/11/05", 82, true);
                AddMessage(1, "anyone@acompany.com", "Re: You're hired", "10/11/05", 6, false);
                ItemIndex = axSftTree1.Items.get_ItemIndex(m_InboxFolder);
                axSftTree1.get_Item(ItemIndex).Collapse(false);
            m_OutboxFolder = AddFolder("Outbox", "Mail about to be sent", 2);
                AddMessage(1, "me@mycompany.com", "Re: You're fired", "10/11/05", 5, false);
                AddMessage(1, "anyone@acompany.com", "Re: Why did you say that", "10/10/05", 5, false);
                ItemIndex = axSftTree1.Items.get_ItemIndex(m_OutboxFolder);
                axSftTree1.get_Item(ItemIndex).Collapse(false);
            m_SavedFolder = AddFolder("Saved", "Saved messages", 2);
                AddMessage(1, "me@mycompany.com", "A support question", "10/09/05", 3, false);
                AddMessage(2, "support@softelvdm.com", "Re: A support question", "10/09/05", 88, true);
                AddMessage(3, "me@mycompany.com", "Re: A support question", "10/09/05", 3, false);
                AddMessage(1, "me@mycompany.com", "Why did you say that", "10/06/05", 5, false);
                AddMessage(2, "anyone@acompany.com", "Re: Why did you say that", "10/10/05", 5, false);
                AddMessage(1, "me@mycompany.com", "You're fired", "10/08/05", 2, false);
                AddMessage(2, "anyone@acompany.com", "Re: You're fired", "10/11/05", 82, false);
                AddMessage(1, "me@mycompany.com", "You're hired", "10/01/05", 4, false);
                AddMessage(1, "anyone@acompany.com", "Re: You're hired", "10/11/05", 6, false);
                ItemIndex = axSftTree1.Items.get_ItemIndex(m_SavedFolder);
                axSftTree1.get_Item(ItemIndex).Collapse(false);
            m_DeletedFolder = AddFolder("Deleted", "Deleted messages", 0);
            axSftTree1.ColumnsObj.MakeOptimal();
            axSftTree1.Items.RecalcHorizontalExtent();
            axSftTree1.Splitter.MakeOptimal();
            // clear column header pictures
            axSftTree1.get_Header(1).Image.Clear();
            axSftTree1.get_Header(2).Image.Clear();
            axSftTree1.get_Header(3).Image.Clear();
            axSftTree1.Items.Current = 0; 
            axSftTree1_CaretChange(this, new _DSftTreeEvents_CaretChangeEvent(0));
        }

        private int AddFolder(string Folder, string Desc, int Count)
        {
            int ItemIndex = axSftTree1.Items.Add(Folder); // add folder
            axSftTree1.get_Cell(ItemIndex, 1).Text = Desc; // add description
            axSftTree1.get_Cell(ItemIndex, 3).Text = Count.ToString(); // add number of messages
            axSftTree1.get_Cell(ItemIndex, 3).Data = Count; // also save number of messages for sorting

            // make the folder name bold
            if (m_BoldFont == null) {
                m_BoldFont = axSftTree1.get_Cell(ItemIndex, 0).Font;
                m_BoldFont.Bold = true;
            }
            axSftTree1.get_Cell(ItemIndex, 0).Font = m_BoldFont;
                
            // if this folder has no messages (ie. dependents), we still want the
            // folder graphic, not the email (leaf) graphic
            if (Count == 0)
                axSftTree1.get_Item(ItemIndex).Image = axSftTree1.Items.ItemImageExpandable;

            return axSftTree1.get_Item(ItemIndex).ID;
        }

        private int AddMessage(short Level, string Email, string Desc, string Dt, int Size, bool Attachment)
        {
            int ItemIndex = axSftTree1.Items.Add(Email); // add folder
            axSftTree1.get_Item(ItemIndex).Level = Level;
            axSftTree1.get_Cell(ItemIndex, 1).Text = Desc; // add description
            axSftTree1.get_Cell(ItemIndex, 2).Text = Dt; // add date
            axSftTree1.get_Cell(ItemIndex, 3).Text = Size.ToString() + "K";
            axSftTree1.get_Cell(ItemIndex, 3).Data = Size; // also save size for sorting
            // if this email has replies (ie. dependents), we still want the
            // email graphic, not the expand folder image
            axSftTree1.get_Item(ItemIndex).Image = axSftTree1.Items.ItemImageLeaf;
            // if the email has an attachment, show the image
            if (Attachment) {
                axSftTree1.get_Cell(ItemIndex, 1).Image.NETImageObject = Attach.Image;
                axSftTree1.get_Cell(ItemIndex, 1).ImageHAlign = SftTreeHAlignConstants.halignSftTreeRight;
            }
            return axSftTree1.get_Item(ItemIndex).ID;
        }

        private void axSftTree1_CaretChange(object sender, AxSftTreeLib70._DSftTreeEvents_CaretChangeEvent e) {
            // set column headers based on selected item
            int ID = axSftTree1.get_Item(e.itemIndex).ID;
            if (ID == m_InboxFolder || ID == m_OutboxFolder || ID == m_SavedFolder || ID == m_DeletedFolder) {
                axSftTree1.get_Header(0).Text = "Folder";
                axSftTree1.get_Header(1).Text = "Description";
                axSftTree1.get_Header(2).Text = ""; // we can use this to merge the adjacent title
                axSftTree1.get_Header(3).Text = "Msgs";
            } else {
                axSftTree1.get_Header(0).Text = "From";
                axSftTree1.get_Header(1).Text = "Subject";
                axSftTree1.get_Header(2).Text = "Received";
                axSftTree1.get_Header(3).Text = "Size";
            }
        }

        private void axSftTree1_ItemClick(object sender, AxSftTreeLib70._DSftTreeEvents_ItemClickEvent e) {
            SftTreeAreaTypeConstants area = (SftTreeAreaTypeConstants) e.areaType; 
            if (area == SftTreeAreaTypeConstants.constSftTreeButton) {
                if (axSftTree1.get_Item(e.itemIndex).Expanded)
                    axSftTree1.get_Item(e.itemIndex).Collapse(true);
                else
                    axSftTree1.get_Item(e.itemIndex).Expand(true, false);
            } else if (area == SftTreeAreaTypeConstants.constSftTreeText) {
                // edit description
                if (e.colIndex == 1)
                    axSftTree1.get_Cell(e.itemIndex, e.colIndex).Edit(0, 0);
            } else if (area == SftTreeAreaTypeConstants.constSftTreeColumnHeader) {
                bool Ascending = true;
                if (axSftTree1.get_Header(e.colIndex).Image.Appearance == SftPictureImageConstants.sftImageSortAsc)
                    Ascending = false;
                
                // we have to sort based on current column headers
                int ItemIndex = axSftTree1.Items.Current;
                int ID = 0;
                if (ItemIndex >= 0)
                    ID = axSftTree1.get_Item(ItemIndex).ID;
                if (ID == m_InboxFolder || ID == m_OutboxFolder || ID == m_SavedFolder || ID == m_DeletedFolder) {
                    // we're on a folder, so sort on folder level
                    if (Ascending) {
                        if (e.colIndex == 3)
                            // last column is sorted by Cell.Data (numeric values)
                            axSftTree1.Items.SortDependents(-1, e.colIndex, SftTreeSortTypeConstants.sortSftTreeAscCellItemData);
                        else
                            axSftTree1.Items.SortDependents(-1, e.colIndex, SftTreeSortTypeConstants.sortSftTreeAscending);
                    } else {
                        if (e.colIndex == 3)
                            axSftTree1.Items.SortDependents(-1, e.colIndex, SftTreeSortTypeConstants.sortSftTreeDscCellItemData);
                        else
                            axSftTree1.Items.SortDependents(-1, e.colIndex, SftTreeSortTypeConstants.sortSftTreeDescending);
                    }
                } else {
                    // we're on a message, sort inside folders
                    // now sort the dependents of all folders
                    ItemIndex = 0;
                    do {
                        if (Ascending) {
                            if (e.colIndex == 3)
                                // last column is sorted by Cell.Data (numeric values)
                                axSftTree1.Items.SortDependents(ItemIndex, e.colIndex, SftTreeSortTypeConstants.sortSftTreeAscCellItemData);
                            else
                                axSftTree1.Items.SortDependents(ItemIndex, e.colIndex, SftTreeSortTypeConstants.sortSftTreeAscending);
                        } else {
                            if (e.colIndex == 3)
                                axSftTree1.Items.SortDependents(ItemIndex, e.colIndex, SftTreeSortTypeConstants.sortSftTreeDscCellItemData);
                            else
                                axSftTree1.Items.SortDependents(ItemIndex, e.colIndex, SftTreeSortTypeConstants.sortSftTreeDescending);
                        }
                        ItemIndex = axSftTree1.get_Item(ItemIndex).NextSibling;
                    } while (ItemIndex >= 0);
                }
                            
                // change column header image
                axSftTree1.get_Header(0).Image.Clear();
                axSftTree1.get_Header(1).Image.Clear();
                axSftTree1.get_Header(2).Image.Clear();
                axSftTree1.get_Header(3).Image.Clear();
                if (Ascending)
                    axSftTree1.get_Header(e.colIndex).Image.Appearance = SftPictureImageConstants.sftImageSortAsc;
                else
                    axSftTree1.get_Header(e.colIndex).Image.Appearance = SftPictureImageConstants.sftImageSortDesc;
                // update column headers by calling CaretChange
                axSftTree1_CaretChange(this, new _DSftTreeEvents_CaretChangeEvent(axSftTree1.Items.Current));
            }
        }

        private void axSftTree1_ItemDblClick(object sender, AxSftTreeLib70._DSftTreeEvents_ItemDblClickEvent e) {
            SftTreeAreaTypeConstants area = (SftTreeAreaTypeConstants) e.areaType; 
            if (area == SftTreeAreaTypeConstants.constSftTreeText || area == SftTreeAreaTypeConstants.constSftTreeButton) {
                // if an item on level 1 or lower is clicked, it's an
                // email message, display message box
                if (axSftTree1.get_Item(e.itemIndex).Level > 0 && area == SftTreeAreaTypeConstants.constSftTreeText) {
                    MessageBox.Show("You could be viewing the message from " + axSftTree1.get_Cell(e.itemIndex, 0).Text +
                        " with the subject '" + axSftTree1.get_Cell(e.itemIndex, 1).Text + "'.");
                } else {
                    // otherwise just expand or collapse the item
                    if (axSftTree1.get_Item(e.itemIndex).Expanded)
                        axSftTree1.get_Item(e.itemIndex).Collapse(true);
                    else
                        axSftTree1.get_Item(e.itemIndex).Expand(true, false);
                }
            } else if (area == SftTreeAreaTypeConstants.constSftTreeColumnRes) {
                if (e.colIndex >= 0) {
                    axSftTree1.get_Column(e.colIndex).MakeOptimal();
                    axSftTree1.Items.RecalcHorizontalExtent();
                } else
                    axSftTree1.Splitter.MakeOptimal();
            }
        }

        private void axSftTree1_EditAllowed(object sender, AxSftTreeLib70._DSftTreeEvents_EditAllowedEvent e) {
            // Only allow editing in column 1
            e.allowed = (e.colIndex == 1);
        }

        private void axSftTree1_EditInitializing(object sender, AxSftTreeLib70._DSftTreeEvents_EditInitializingEvent e) {
          
            // LeftPix/TopPix/WidthPix/HeightPix describes the current cell area
            // we need to return the position and size needed for editing.
            // In this example, we use the height of the control on the form
            // and center it over the cell.
            
            e.topPix = e.topPix + (e.heightPix - EditControl.Height) / 2;
            e.heightPix = EditControl.Height;
            
            // Set the text in the control used for cell editing and
            // set other control-specific properties
            EditControl.Width = 200;
            EditControl.Text = axSftTree1.get_Cell(e.editIndex, e.editCol).Text;
            EditControl.SelectionStart = 0;
            EditControl.SelectionLength = 999;

            // Return the control's window handle
            e.window = (int) EditControl.Handle;
            e.vData = EditControl;

            // Define navigation keys
            // VK_TAB
            axSftTree1.CellEditIntercept(9, SftTreeCellEditInterceptStyleConstants.cellEditInterceptSftTreeChar | SftTreeCellEditInterceptStyleConstants.cellEditInterceptSftTreeControlChar | SftTreeCellEditInterceptStyleConstants.cellEditInterceptSftTreeShiftChar);
            // VK_RETURN
            axSftTree1.CellEditIntercept(13, SftTreeCellEditInterceptStyleConstants.cellEditInterceptSftTreeChar | SftTreeCellEditInterceptStyleConstants.cellEditInterceptSftTreeControlChar | SftTreeCellEditInterceptStyleConstants.cellEditInterceptSftTreeShiftChar);
            // VK_HOME
            axSftTree1.CellEditIntercept(36, SftTreeCellEditInterceptStyleConstants.cellEditInterceptSftTreeControlChar);
            // VK_END
            axSftTree1.CellEditIntercept(35, SftTreeCellEditInterceptStyleConstants.cellEditInterceptSftTreeControlChar);
            // VK_UP
            axSftTree1.CellEditIntercept(38, SftTreeCellEditInterceptStyleConstants.cellEditInterceptSftTreeChar | SftTreeCellEditInterceptStyleConstants.cellEditInterceptSftTreeControlChar | SftTreeCellEditInterceptStyleConstants.cellEditInterceptSftTreeShiftChar);
            // VK_DOWN
            axSftTree1.CellEditIntercept(40, SftTreeCellEditInterceptStyleConstants.cellEditInterceptSftTreeChar | SftTreeCellEditInterceptStyleConstants.cellEditInterceptSftTreeControlChar | SftTreeCellEditInterceptStyleConstants.cellEditInterceptSftTreeShiftChar);
        }

        private void axSftTree1_EditNavigating(object sender, AxSftTreeLib70._DSftTreeEvents_EditNavigatingEvent e) {
            // Process key pressed
            axSftTree1.EditNavigate(e.key, e.shift);
        }

        private void axSftTree1_EditValidate(object sender, AxSftTreeLib70._DSftTreeEvents_EditValidateEvent e) {
            // Validate the new cell contents
            string s = EditControl.Text;
            s = s.Trim();
            if (s.Length <= 0) {
                MessageBox.Show("Please enter a description.");
                e.inputValid = false;
            }
        }

        private void axSftTree1_EditEnding(object sender, AxSftTreeLib70._DSftTreeEvents_EditEndingEvent e) {
            // Save the new cell contents
            if (e.saveInput)
                axSftTree1.get_Cell(e.editIndex, e.editCol).Text = EditControl.Text;
            Control ctrl = (Control) e.vData;
            ctrl.Visible = false;
            ctrl.Enabled = false;
        }
    }
}